package com.lxd.filter.Impl;


import com.lxd.common.constants.CacheConstant;
import com.lxd.common.enums.ExceptionEnums;
import com.lxd.common.exception.StrategyException;
import com.lxd.common.model.StandardSubmit;
import com.lxd.feign.cacheClient;
import com.lxd.filter.CheckFilter;
import com.lxd.utils.ClientBalanceUtil;
import com.lxd.utils.ErrorSendMsgUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service(value = "fee")
@Slf4j
public class FeeStrategyFilter implements CheckFilter {

    @Autowired
    private cacheClient client;

    @Autowired
    private ErrorSendMsgUtil errorSendMsgUtil;

    private final String BALANCE = "balance";


    @Override
    public void check(StandardSubmit submit) {
        log.info("【策略模块-扣费校验】   校验ing…………");
        //1、获取submit中封装的金额
        Long fee = submit.getFee();
        log.info("【策略模块-扣费校验】金额fee={}",fee);
        Long clientId = submit.getClientId();
        //2、调用Redis的hashIncrBy扣减具体的金额
        Long amount = client.hIncrBy(CacheConstant.CLIENT_BALANCE + clientId, BALANCE, -fee);
        log.info("amout={}",amount);
        //3、获取当前客户的欠费金额的限制（外部方法调用，暂时写死为10000）
        Long amountLimit = ClientBalanceUtil.getClientAmountLimit(submit.getClientId());

        //4、判断扣减过后的金额，是否超出了金额限制
        if(amount < amountLimit) {
            log.info("【策略模块-扣费校验】   扣除费用后，超过欠费余额的限制，无法发送短信！！");
            //5、如果超过了，需要将扣除的费用增加回去，并且做后续处理
            client.hIncrBy(CacheConstant.CLIENT_BALANCE + clientId, BALANCE, fee);
            submit.setErrorMsg(ExceptionEnums.BALANCE_NOT_ENOUGH.getMsg());
            errorSendMsgUtil.sendWriteLog(submit);
            errorSendMsgUtil.sendPushReport(submit);
            throw new StrategyException(ExceptionEnums.BALANCE_NOT_ENOUGH);
        }
        log.info("【策略模块-扣费校验】   扣费成功！！");
    }
}